package com.yingyi.mtw.base.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;


public class Open56Client {
	
	private final String appkey;
	private final String secret;
	private String domain="http://oapi.56.com";
	private String interfaceURL="/video/getVideoInfo.json";
	
	private String access_token;
	
	public Open56Client(String appkey,String secret) {
		// TODO Auto-generated constructor stub
		if("".equals(appkey) || "".equals(secret)){
			System.out.println("appkey 或 secret均不能为空");
		}
		//初始化appkey和secret
		this.appkey = appkey;
		this.secret = secret;
	}
	
	//获取视频信息
	public String  getVideoInfoApp(String vid){
        String url=domain+interfaceURL;
        try {
			vid = URLEncoder.encode(vid,"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
        HashMap<String, String> params = new HashMap<String, String>();
        
        params.put("vid", vid);
        
        url = url+"?"+signRequest(params);
        
        return httpCall(url);
   }
	
	//统一的http请求
	private String httpCall(String url){
		
		HttpClient client = new HttpClient();	//实例化httpClient
		HttpMethod method = new GetMethod(url);	//
		String responseContent = "";
		try {
			client.executeMethod(method);		//执行		

			InputStream jsonStr;

			jsonStr = method.getResponseBodyAsStream();			
				
			ByteArrayOutputStream   baos   =   new   ByteArrayOutputStream(); 
			
	        int   i=-1; 
	        while((i=jsonStr.read())!=-1){ 
	        	baos.write(i); 
	        }
	        
	        responseContent = baos.toString(); 
	        
	        jsonStr.close();
	        baos.close();
	        method.releaseConnection();
	        
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return responseContent;
	}
	
    //签名方法实现，并构造一个参数串
    private String signRequest(HashMap< String, String> params){
    	    	
    	String req = getMD5Str(mapToString(params));	//第一轮次计算 MD5加密
    	
    	//获取时间戳
    	Date date = new Date();
    	long time = date.getTime();
    	//mysq 时间戳只有10位 要做处理
    	String ts = time + "";
    	ts = ts.substring(0, 10);
    	
    	params.put("sign", getMD5Str(req+"#"+this.appkey+"#"+this.secret+"#"+ts));   //第二轮次计算 MD5加密
    	params.put("appkey", this.appkey);
    	params.put("ts", ts);
    	
    	return mapToString(params);
    }
    
    //将 map 中的参数及对应值转换为字符串
    private String mapToString(HashMap<String, String> params){
    	Object[] array = params.keySet().toArray();
    	
    	Arrays.sort(array);
    	
    	String str = "";
    	//for(int i = array.length-1;i>=0;i--){
    	//	String key = array[i].toString();
    		//if(i!=0){
    			//str += key+"="+params.get(key)+"&";
    		//}else{
    			//str += key+"="+params.get(key);
    		//}
    //	}
		
		for(int i =0;i<array.length;i++){
    		String key = array[i].toString();
    		if(i!=(array.length-1)){
    			str += key+"="+params.get(key)+"&";
    		}else{
    			str += key+"="+params.get(key);
    		}
    	}
    	return str;
    }

	//设置参数值
 	public void setPara(String sdomain, String sinterfaceURL)
	    {
	    	this.domain = sdomain;
	    	this.interfaceURL = sinterfaceURL;
	    }
 	
 	//md5
 	  private String getMD5Str(String str) {  
          MessageDigest messageDigest = null;  
   
         try {  
              messageDigest = MessageDigest.getInstance("MD5");  
   
              messageDigest.reset();  
   
              messageDigest.update(str.getBytes("UTF-8"));  
          } catch (NoSuchAlgorithmException e) {  
              System.out.println("NoSuchAlgorithmException caught!");  
              System.exit(-1);  
          } catch (UnsupportedEncodingException e) {  
              e.printStackTrace();  
          }  
   
         byte[] byteArray = messageDigest.digest();  
   
          StringBuffer md5StrBuff = new StringBuffer();  
   
         for (int i = 0; i < byteArray.length; i++) {              
             if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)  
                  md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));  
             else  
                  md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));  
          }  
   
         return md5StrBuff.toString();  
      }  
    
}
